#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
# @version: v1.0
# @author : wlis
# @Email : 1259319710@qq.com
# @Project : G-Carbon Bio
# @File : email_service.py
# @Software: PyCharm
# @time: 2025/1/25 12:15
# @description : 邮件发送类
"""
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from email_notifier.email_config import EMAIL_CONFIG  # 从配置文件中导入邮件配置

class EmailService:
    def __init__(self):
        """
        初始化 EmailService 实例。

        从配置文件获取SMTP服务器信息和用户凭证。
        """
        self.smtp_server = EMAIL_CONFIG['SMTP_SERVER']
        self.smtp_port = EMAIL_CONFIG['SMTP_PORT']
        self.username = EMAIL_CONFIG['USERNAME']
        self.password = EMAIL_CONFIG['PASSWORD']

    def flatten(self, lst):
        """将嵌套列表展平为一个平面列表"""
        flat_list = []
        for item in lst:
            if isinstance(item, list):
                flat_list.extend(self.flatten(item))  # 递归处理嵌套列表
            else:
                flat_list.append(item)
        return flat_list

    def send_email(self, recipient, subject, email_title, html_content):
        """
        发送HTML格式的电子邮件。

        :param recipient: 收件人邮箱地址，可以是字符串、列表或元组，支持嵌套列表
        :param subject: 邮件主题
        :param email_title: 发件人的姓名或标识（用于邮件的“From”字段）
        :param html_content: 邮件的HTML内容
        """
        smtp_obj = None  # 初始化smtp_obj为None，以便在finally块中检查
        try:
            smtp_obj = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
            smtp_obj.set_debuglevel(1)  # 调试级别
            smtp_obj.login(self.username, self.password)

            # 创建MIMEText对象，包含HTML邮件内容
            message = MIMEText(html_content, 'html', 'utf-8')
            message['Subject'] = Header(subject, 'utf-8')
            message['From'] = formataddr((str(Header(email_title, 'utf-8')), self.username))

            # 处理收件人列表，展平嵌套列表
            recipients = self.flatten(recipient)
            if not recipients:
                raise ValueError("没有有效的收件人")

            # 设置邮件的To字段
            message['To'] = Header(', '.join(recipients), 'utf-8')

            # 发送邮件
            smtp_obj.sendmail(self.username, recipients, message.as_string())
            print(f"邮件发送成功: {recipients}")
        except smtplib.SMTPException as e:
            print(f"发送邮件至 {recipients} 失败: {getattr(e, 'smtp_code', 'N/A')}, {getattr(e, 'smtp_error', str(e))}")
        except Exception as e:
            print(f"发送邮件至 {recipients} 失败: {e}")
        finally:
            if smtp_obj:
                smtp_obj.quit()  # 确保连接被关闭（如果它已被创建）


# # 使用示例（可在其他模块中调用）
# if __name__ == "__main__":
#     # 初始化邮件服务实例
#     email_service = EmailService()
#
#     # 示例收件人和邮件内容
#     recipients = ["recipient@example.com"]
#     subject = "测试主题"
#     rendered_html = "<h1>这是邮件内容</h1>"
#
#     # 发送邮件
#     for recipient in recipients:
#         email_service.send_email(recipient, subject, "邮件标题", rendered_html)
